package com.shhm.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.shhm.common.dto.response.AjaxResultPlus;
import com.shhm.common.entity.admin.SysUser;
import com.shhm.common.utils.CaptchaUtil;
import com.shhm.common.utils.IpUtil;
import com.shhm.common.utils.RedisUtil;
import com.shhm.common.utils.ResponseUtil;
import com.shhm.system.dto.request.RegisterReq;
import com.shhm.system.mapper.LoginMapper;
import com.shhm.system.mapper.RegisterMapper;
import com.shhm.system.mapper.SysUserRoleMapper;
import com.shhm.system.service.RegisterService;
import com.shhm.system.service.SysUserRoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author JackZ
 * @version 1.0
 * @description: TODO
 * @date 2025/9/18 下午4:21
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    @Qualifier("captchaProducerMath") // 指定数学验证码 Bean
    private DefaultKaptcha kaptchaBeanMath;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    
    @Override
    public AjaxResultPlus register(SysUser req,String captcha, HttpServletRequest request) {
        String passCheck= CaptchaUtil.checkCaptcha(request,redisTemplate, Integer.valueOf(captcha),RedisUtil.REDIS_REGISTER_KEY);
        if(!passCheck.equals("pass")) return AjaxResultPlus.warn(passCheck);
        String encode = passwordEncoder.encode(req.getPassword());
        req.setPassword(encode);
        req.createLocalDateTime();
        return ResponseUtil.sqlExeIsSuccess(registerMapper.insert(req),"注册失败!");
    }

    @Override
    public AjaxResultPlus getCaptcha(HttpServletRequest request) throws IOException {
        return CaptchaUtil.getCaptcha(request,redisTemplate,kaptchaBeanMath,RedisUtil.REDIS_REGISTER_KEY);
    }
}
